package com.thingsgrid.physicalmodel.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.thingsgrid.physicalmodel.entity.*;
import com.thingsgrid.physicalmodel.service.IPhysicalModelService;
import com.thingsgrid.system.user.entity.User;
import com.thingsgrid.system.user.feign.IUserClient;
import org.springblade.core.tool.api.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;


@Service
public class PhysicalModelServiceImpl implements IPhysicalModelService {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private IUserClient userClient;
	/**
	 *
	 *新增
	 * @author 陈学栋
	 * @date 2019/9/11 13:25
	 */
	@Override
	public Boolean savePhysical(String obj,Integer userId) {
		//前台接受的obj转化为PhysicalModel对象
		PhysicalModel object = JSONObject.parseObject(obj,PhysicalModel.class);
		PhysicalModel model = new PhysicalModel();
		model.setPhysicalModelId(UUID.randomUUID().toString());
		model.setPhysicalName(object.getPhysicalName());
		model.setPhysicalDescribe(object.getPhysicalDescribe());
		model.setPhysicalAttribute(object.getPhysicalAttribute());
		model.setPhysicalEvent(object.getPhysicalEvent());
		model.setPhysicalServer(object.getPhysicalServer());
		//创建时间
		Date currentTime = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(currentTime);
		model.setCreateTime(dateString);
		//通过userId查询用户信息
		Long nUserId = Long.valueOf(userId);
		R<User> user = userClient.userInfoById(nUserId);
		User data = user.getData();
		model.setCreateAuthor(data.getAccount());
		mongoTemplate.save(model,"physical_model");
		return true;
	}
	/**
	 * 删除
	 * @param physicalModelId
	 */
	@Override
	public Boolean removePhysical(String physicalModelId) {
		Query query = new Query();
		query.addCriteria(Criteria.where("physicalModelId").is(physicalModelId));
		DeleteResult deleteResult = mongoTemplate.remove(query, PhysicalModel.class, "physical_model");
		if(deleteResult.getDeletedCount() != 0){
			return true;
		}
		return false;
	}

	/**
	 * 更新
	 * @param obj
	 */
	@Override
	public Boolean updatePhysical(String obj) {
		PhysicalModel object = JSONObject.parseObject(obj,PhysicalModel.class);
		Query query = new Query();
		query.addCriteria(Criteria.where("physicalModelId").is(object.getPhysicalModelId()));
		Update update = new Update();
		update.set("physicalName",object.getPhysicalName());
		update.set("physicalDescribe",object.getPhysicalDescribe());
		update.set("physicalAttribute",object.getPhysicalAttribute());
		update.set("physicalService",object.getPhysicalServer());
		update.set("physicalEvent",object.getPhysicalEvent());
		UpdateResult updateResult = mongoTemplate.updateFirst(query, update, PhysicalModel.class, "physical_model");
		if(updateResult.getModifiedCount()==1){
			return true;
		}
		return false;
	}

	/**
	 * 查询所有
	 * @return
	 */
	@Override
	public List<PhysicalModel> findAll() {
		return mongoTemplate.find(new Query(), PhysicalModel.class, "physical_model");

	}

	/**
	 * 根据id查找
	 * @param  physicalModelId
	 * @return
	 */
	@Override
	public PhysicalModel findPhysicalById(String physicalModelId) {
		Query query = new Query();
		query.addCriteria(Criteria.where("physicalModelId").is(physicalModelId));
		PhysicalModel physicalModel = mongoTemplate.findOne(query,PhysicalModel.class,"physical_model");
		assert physicalModel != null;
		if(physicalModel.getPhysicalEvent().size()>0){
			for(PhysicalEvent physicalEvent:physicalModel.getPhysicalEvent()){
				if(physicalEvent.getOutputParams().size()>0){
					StringBuilder outPutStr = new StringBuilder();
					for(OutputParams outputParams:physicalEvent.getOutputParams()){
						outPutStr.append(outputParams.getParamName()).append(",");
					}
					physicalEvent.setEventStr(outPutStr.toString());
				}
			}
		}
		if(physicalModel.getPhysicalServer().size()>0){
			for(PhysicalServer physicalServer:physicalModel.getPhysicalServer()){
				if(physicalServer.getOutputParams().size()>0){
					StringBuilder outPutStr = new StringBuilder();
					for(OutputParams outputParams:physicalServer.getOutputParams()){
						outPutStr.append(outputParams.getParamName()).append(",");
					}
					physicalServer.setServerOutStr(outPutStr.toString());
				}
				if(physicalServer.getOutputParams().size()>0){
					StringBuilder intPutStr = new StringBuilder();
					for(InputParams inputParams:physicalServer.getInputParams()){
						intPutStr.append(inputParams.getParamName()).append(",");
					}
					physicalServer.setServerInputStr(intPutStr.toString());
				}
			}
		}
		return physicalModel;
	}

	/**
	 * 分页查找
	 * @param pageIndex
	 * @param pageSize
	 * @return
	 */
	@Override
	public Map<String, Object> findAll(Integer pageIndex, Integer pageSize) {
		HashMap<String, Object> map = new HashMap<>();
		Query query = new Query().skip((pageIndex - 1) * pageSize).limit(pageSize);
		List<PhysicalModel> list = mongoTemplate.find(query, PhysicalModel.class, "physical_model");
		long count = mongoTemplate.count(query, PhysicalModel.class, "physical_model");
		map.put("physicalModelList",list);
		map.put("total",count);
		return map;
	}

	/**
	 *通过名称查询
	 * @param physicalName
	 * @return
	 */
	@Override
	public List<PhysicalModel> findOneByName(String physicalName) {
		return mongoTemplate.find(new Query(Criteria.where("physicalName").is(physicalName)), PhysicalModel.class, "physical_model");
	}
}
